import re

from django_redis import get_redis_connection
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from rest_framework import serializers
from django.conf import settings
from rest_framework_jwt.settings import api_settings

from oauth.models import OAuthQQUser
from users.models import User


class QQAuthUserSerializer(serializers.ModelSerializer):
    access_token = serializers.CharField(write_only=True)
    sms_code=serializers.CharField(max_length=6,min_length=6,write_only=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    token = serializers.CharField(read_only=True)
    class Meta:
        model = User
        fields = ('password','mobile','sms_code','access_token','username','token')
        read_only_fields = ('username',) #只读
        extar_kwagrs = {
            'password': {
                'max_length': 20,
                'min_length': 8,
                "write_only": True,
                'error_messages': {
                    'max_length': '密码过长',
                    'min_length': '密码过短'
                }

            },
            'mobile': {
                'max_length': 11,
                'min_length': 11,

            }

        }

    def validate(self, attrs):
        #access_token 验证
        tjs = TJS(settings.SECRET_KEY,300)
        try:
            data = tjs.loads(attrs['access_token'])
        except:

            raise serializers.ValidationError('错误的token')
        openid = data.get('openid')
        #添加解密出的数据
        attrs['openid'] = openid

        #验证短信
        # 从redis获取真是短信验证码
        conn = get_redis_connection('verify')

        # 获取数据
        real_sms_code = conn.get('sms_%s' % attrs['mobile'])

        # 判断是否过期
        if not real_sms_code:
            raise serializers.ValidationError('验证码已过期')
        # 转换格式
        real_sms_code = real_sms_code.decode()
        # 比对验证
        if attrs['sms_code'] != real_sms_code:
            raise serializers.ValidationError('验证码错误')


        #验证用户
        try:
            user = User.objects.get(mobile=attrs['mobile'])
        except:
            return attrs
        else:
            #验证密码
            if  user.check_password(attrs['password']):
                attrs['user'] = user
                return attrs
            else:
                raise serializers.ValidationError('密码错误')

    def create(self,validates_data):

        #获取user判断用户是否注册
        user = validates_data.get('user')

        if user is None:
            #用户未注册,进行注册
            user = User.objects.create_user(username=validates_data['mobile'],password=validates_data['password'],mobile=validates_data['mobile'])

        #进行绑定
        OAuthQQUser.objects.create(user=user,openid=validates_data['openid'])
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)  # 保存到载荷部分
        token = jwt_encode_handler(payload)  # 生成TOKEN

        user.token = token  # 序列化返回要指明在序列化中
        return user